package com.quanyan.platform.service.impl;


import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.RespPlaceClubInfo;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.comment.reqeust.ReqUserCollectQuery;
import com.quanyan.comment.response.RespUserCollect;
import com.quanyan.comment.serviceFacade.UserCollectServiceFacade;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.PlaceDubboProvider;
import com.quanyan.platform.client.IPlaceDubboService;
import com.quanyan.platform.response.GatherPlaceResponse;
import com.quanyan.platform.response.MyPlaceResponse;
import com.quanyan.platform.service.IplaceService;
import com.quanyan.user.response.RespPlaceVideoInfo;
import com.quanyan.user.serviceFacade.VideoServiceFacade;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static com.quanyan.api.APIResponse.returnFail;
import static com.quanyan.api.APIResponse.returnSuccess;

/**
 * Created by jingliu on 17/3/10.
 */
@Service("iPlaceDubboService")
public class PlaceDubboServiceImpl implements IPlaceDubboService,IplaceService {
    private static final Logger logger = LoggerFactory.getLogger(PlaceDubboServiceImpl.class);
    @Autowired
	PlaceClient placeClient;
	@Autowired
	UserCollectServiceFacade userCollectServiceFacade;
	@Autowired
	ClubOpenService clubOpenService;
	@Autowired
	VideoServiceFacade videoServiceFacade;
	@Value("${c.gather.place.address}")
	String address;
	@Value("${c.gather.place.url}")
	String url;

	public List<PlaceDubboProvider> getPlaceByTerm(List<Integer> placeIds, Double lat, Double lng){
		Map<Integer,PlaceDubboProvider> map = null;
		try{
			long currentMiles = System.currentTimeMillis();
			map = placeClient.getPlaceByTerm(placeIds, lat ,lng);
			logger.debug("==========调用场馆后台获取场馆信息 Request:{},耗时：{}ms=========", placeIds,(System.currentTimeMillis() - currentMiles));
		}catch (Exception e){
			logger.error("调用场馆服务异常:{}", e.toString());
		}
		if (MapUtils.isNotEmpty(map)){
			List<PlaceDubboProvider> list = new ArrayList<>();
			for (Map.Entry<Integer, PlaceDubboProvider> entry : map.entrySet()){
				list.add(entry.getValue());
			}
			return list;
		}
		return null;
	}

	@Override
	public Map<Integer, GatherPlaceResponse> getMasterByPlaceIds(List<Integer> placeIds,
	                                                             Integer pageNum, Integer pageSize) {
		Map<Integer, GatherPlaceResponse> map = new HashMap<>();
		List<GatherPlaceResponse> gatherPlaceResponses = this.getGatherPlaceInfo(placeIds, pageNum, pageSize);
		if (CollectionUtils.isEmpty(gatherPlaceResponses)){
			return map;
		}
		for (GatherPlaceResponse gatherPlaceResponse : gatherPlaceResponses){
			map.put(gatherPlaceResponse.getPlace_id(), gatherPlaceResponse);
		}
		return map;
	}

	private Map getJsonParam(){
		Map param = new HashMap<>();
		param.put("ver","2");
		param.put("protocol_ver",1);
		param.put("currentUid",0);
		return param;
	}


	public APIResponse<List<PlaceDubboProvider>> getColPlaces(Integer uid, Double lat, Double lng,
	                                                          Integer pageNum, Integer pageSize){
		ReqUserCollectQuery reqUserCollectQuery = new ReqUserCollectQuery();
		reqUserCollectQuery.setSystemCode(Constants.PLACE_SYSTEM_CODE);
		reqUserCollectQuery.setBusinessCode(Constants.PLACE_BOOKING_CODE);
		reqUserCollectQuery.setUserId(uid);
		pageNum = null == pageNum ? 0 : pageNum;
		pageSize = null == pageSize ? 100 : pageSize;
		reqUserCollectQuery.setPageNum(pageNum);
		reqUserCollectQuery.setPageSize(pageSize);

		long currentMiles = System.currentTimeMillis();
		APIResponse<PageObj<List<RespUserCollect>>> apiResponse = userCollectServiceFacade
				.queryUserCollect(reqUserCollectQuery);
		logger.debug("==========调用用户中心获取收藏列表服务 Request:{},耗时：{}ms=========", reqUserCollectQuery,(System.currentTimeMillis() - currentMiles));
		
		if (!apiResponse.isRet()) {
			return returnFail("调用收藏列表服务失败");
		}
		PageObj<List<RespUserCollect>> datas1 = apiResponse.getData();
		if (StringUtils.isEmpty(datas1) && CollectionUtils.isEmpty(datas1.getItems())) {
			logger.debug("=========Uid:{}==========没有收藏列表", uid);
			return returnSuccess(null);
		}
		List<RespUserCollect> datas = datas1.getItems();
		if (CollectionUtils.isEmpty(datas)) {
			logger.debug("=========Uid:{}==========没有收藏列表", uid);
			return returnSuccess(null);
		}
		List<Integer> placeIds = new ArrayList<>();
		for (int i = 0, len = datas.size(); i < len; i++) {
			RespUserCollect respUserCollect = datas.get(i);
			Integer placeid = Integer.valueOf(respUserCollect.getBusinessId());
			placeIds.add(placeid);
		}
		if (CollectionUtils.isEmpty(placeIds)){
			logger.debug("=========Uid:{}==========没有收藏列表", uid);
			return returnSuccess(null);
		}
		List<PlaceDubboProvider> list = getPlaceByTerm(placeIds, lat, lng);
		return APIResponse.returnSuccess(list);
	}

	@Override
	public APIResponse<List<PlaceDubboProvider>> getOrderPlaces(Integer uid, Double lat, Double lng) {
		
		    long currentMiles = System.currentTimeMillis();
			APIResponse<List<Integer>> apiResponse = placeClient.findOrdersByUid(uid);
			logger.debug("=========调用场馆后台获取用户下单的场馆信息 Reqest:{} ,Response:{}, 耗时: {}ms ==========", uid,JSON.toJSONString(apiResponse),(System.currentTimeMillis() - currentMiles));
			
			if (!apiResponse.isRet()){
				return returnFail("调用场馆获取订单对应场馆服务失败");
			}
			List<Integer> placeIds = apiResponse.getData();
		if (CollectionUtils.isEmpty(placeIds)){
			return APIResponse.returnSuccess(null);
		}
		List<PlaceDubboProvider> list = getPlaceByTerm(placeIds, lat, lng);
		if (CollectionUtils.isEmpty(list)){
			return APIResponse.returnSuccess(null);
		}
		return APIResponse.returnSuccess(list);
	}

	@Override
	public APIResponse<MyPlaceResponse> getStartingPlace(Integer uid) {
		ReqUserCollectQuery reqUserCollectQuery = new ReqUserCollectQuery();
		reqUserCollectQuery.setSystemCode(Constants.PLACE_SYSTEM_CODE);
		reqUserCollectQuery.setBusinessCode(Constants.PLACE_BOOKING_CODE);
		reqUserCollectQuery.setUserId(uid);
		reqUserCollectQuery.setPageNum(0);
		reqUserCollectQuery.setPageSize(100);

		APIResponse<PageObj<List<RespUserCollect>>> apiResponse = userCollectServiceFacade
				.queryUserCollect(reqUserCollectQuery);
		APIResponse<List<Integer>> response = placeClient.findOrdersByUid(uid);
		if (!apiResponse.isRet()){
			return returnFail("调用场馆获取订单对应场馆服务失败");
		}
		Integer placeNum = 0;

		if (!apiResponse.isRet()) {
			return returnFail("调用收藏列表服务失败");
		}
		List<Integer> orderPlaceIds = response.getData();
		if (CollectionUtils.isEmpty(orderPlaceIds)){
			logger.debug("=========Uid:{}==========没有订单列表", uid);
		}
		PageObj<List<RespUserCollect>> datas1 = apiResponse.getData();
		if (StringUtils.isEmpty(datas1) && CollectionUtils.isEmpty(datas1.getItems())) {
			logger.debug("=========Uid:{}==========没有收藏列表", uid);

		}
		List<RespUserCollect> datas = datas1.getItems();
		if (CollectionUtils.isEmpty(datas)) {
			logger.debug("=========Uid:{}==========没有收藏列表", uid);
		}

		List<Integer> placeIds = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(datas)){
			for (int i = 0, len = datas.size(); i < len; i++) {
				RespUserCollect respUserCollect = datas.get(i);
				Integer placeid = Integer.valueOf(respUserCollect.getBusinessId());
				placeIds.add(placeid);
			}
		}
		if (CollectionUtils.isEmpty(placeIds)){
			placeNum += 0;
		}
		if (CollectionUtils.isNotEmpty(orderPlaceIds)){
			placeIds.addAll(orderPlaceIds);
			List<Integer> places = new ArrayList<>(new HashSet<>(placeIds));
			placeNum += places.size();
		}else {
			placeNum += placeIds.size();
		}

		MyPlaceResponse myPlaceResponse = new MyPlaceResponse();
		myPlaceResponse.setPlaceNum(placeNum);

		APIResponse<MyPlaceResponse> resp = placeClient.findEarlyPlace(uid);
		if (null != resp && resp.isRet()){
			MyPlaceResponse my = resp.getData();
			my.setPlaceNum(placeNum);
			return APIResponse.returnSuccess(my);
		}
		return APIResponse.returnSuccess(myPlaceResponse);
	}

	@Override
	public List<GatherPlaceResponse> getGatherPlaceInfo(List placeIds, Integer pageNum, Integer pageSize) {
		List<GatherPlaceResponse> gatherPlaceResponseList = new ArrayList<>();
		if (CollectionUtils.isEmpty(placeIds)){
			return gatherPlaceResponseList;
		}

		String requestUrl = this.address + this.url;

		try {
			Map param = getJsonParam();
			param.put("place_id",placeIds);
			param.put("page", pageSize);
			param.put("next", pageNum);
			String result = HttpClientUtils.postJson(requestUrl, GsonUtils.toJson(param));
			logger.debug("聚集地批量获取达人活动:{}", result);
			if (!StringUtils.isEmpty(result)) {
				JSONObject jsonObjectResult = JSON.parseObject(result);
				if(jsonObjectResult.get("errcode").equals(200)){
					Object o = jsonObjectResult.get("data");
					if (null != o){
						List<GatherPlaceResponse> lstDoyen = JSONObject.parseArray(o.toString(), GatherPlaceResponse.class);
						return lstDoyen;
					}
				}
			}
		} catch (Exception e) {
			logger.error("聚集地批量获取达人活动失败！{}",e);
		}
		return gatherPlaceResponseList;
	}

	@Override
	public APIResponse<Map<String, List<PlaceDubboProvider>>> getMyPlaces(Integer uid, Double lat, Double lng) {
		Map<String, List<PlaceDubboProvider>> map = new ConcurrentHashMap<>();
		APIResponse<List<PlaceDubboProvider>> apiResponseCol = getColPlaces(uid, lat, lng, 0, 100);
		APIResponse<List<PlaceDubboProvider>> apiResponseOrder = getOrderPlaces(uid, lat, lng);

        if (null != apiResponseCol && apiResponseCol.isRet() && apiResponseCol.getData() != null) {
            map.put("collect", apiResponseCol.getData());
		}
        if (null != apiResponseOrder && apiResponseOrder.isRet() && apiResponseOrder.getData() != null) {
            map.put("order", apiResponseOrder.getData());
		}

		//从订单中去重复场馆
		if (CollectionUtils.isNotEmpty(map.get("collect"))
				&& CollectionUtils.isNotEmpty(map.get("order"))){
			List<PlaceDubboProvider> placeDubboProviderCollectList = map.get("collect");
			List<PlaceDubboProvider> placeDubboProviderOrderList = map.get("order");

			List<PlaceDubboProvider> placeDubboProviderCollectListTmp = new ArrayList<>();
			placeDubboProviderCollectListTmp.addAll(placeDubboProviderOrderList);
			for (PlaceDubboProvider placeDubboProvider : placeDubboProviderCollectListTmp){
				if (null == placeDubboProvider){
					continue;
				}
				for (PlaceDubboProvider model : placeDubboProviderCollectList){
					if (model.getPlaceId().equals(placeDubboProvider.getPlaceId())){
						placeDubboProviderOrderList.remove(placeDubboProvider);
						break;
					}
				}
			}
			map.put("order", placeDubboProviderOrderList);
		}

		return APIResponse.returnSuccess(map);
	}
	
	@Override
	public Map<Integer, List<RespPlaceClubInfo>> selectClubByPlaceIds(List<Integer> placeIds,
	                                                                  int pageNum, int pageSize,int categoryId) {
		Map<Integer, List<RespPlaceClubInfo>> map = new HashMap<>();

		Map<Integer, List<RespPlaceClubInfo>> respPlaceClubInfoMap = null;
		try {
			respPlaceClubInfoMap = clubOpenService.selectClubByPlaceIds(placeIds,
					Constants.DEFAULT_PAGE_INDEX, pageSize,categoryId);
			logger.debug("Map<Integer, List<RespPlaceClubInfo>> respPlaceClubInfoMap:{}",
					JSON.toJSONString(respPlaceClubInfoMap));
		} catch (Exception e) {
			logger.error("调用聚集地对应俱乐部服务异常:{}",e);
		}
		if (MapUtils.isEmpty(respPlaceClubInfoMap)){
			return map;
		}
		return respPlaceClubInfoMap;
	}

	@Override
	public Map<Integer, List<RespPlaceClubInfo>> selectActivityByPlaceIds(List<Integer> placeIds,
	                                                                      int pageNum, int pageSize,int categoryId) {
		Map<Integer, List<RespPlaceClubInfo>> map = new HashMap<>();

		Map<Integer, List<RespPlaceClubInfo>> respPlaceClubInfoMap
				= null;
		try {
			respPlaceClubInfoMap = clubOpenService
					.selectActivityByPlaceIds(placeIds, Constants.DEFAULT_PAGE_INDEX, pageSize,categoryId);
			logger.debug("Map<Integer, List<RespPlaceClubInfo>> respPlaceClubInfoMap:{}",
					JSON.toJSONString(respPlaceClubInfoMap));
		} catch (Exception e) {
			logger.error("调用聚集地对应俱乐部活动服务异常:{}",e);
		}
		if (MapUtils.isEmpty(respPlaceClubInfoMap)){
			return map;
		}
		return respPlaceClubInfoMap;
	}

	@Override
	public Map<Integer, RespPlaceVideoInfo> getPlaceVideoInfo(List<Integer> placeIds) {
		Map<Integer, RespPlaceVideoInfo> map = new HashMap<>();

		APIResponse<List<RespPlaceVideoInfo>> response = null;
		try {
			response = videoServiceFacade.getPlaceVideoInfo(placeIds);
			logger.debug("APIResponse<List<RespPlaceVideoInfo>> response:{}", JSON.toJSONString(response));
		} catch (Exception e) {
			logger.error("调用聚集地对应视频服务异常:{}",e);
		}
		if (null != response && response.isRet()){
			List<RespPlaceVideoInfo> respPlaceVideoInfos = response.getData();
			if (CollectionUtils.isNotEmpty(respPlaceVideoInfos)){
				for (RespPlaceVideoInfo respPlaceVideoInfo : respPlaceVideoInfos){
					map.put(respPlaceVideoInfo.getPlaceId(), respPlaceVideoInfo);
				}
			}
			return map;
		}

		return map;
	}

}
